package com.wushi.lenovo.asia5b.app_ui.credit.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.ListPopupWindow;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.mvp.base.BaseMvpActivity;
import com.mvp.base.model.ResultModel;
import com.mvp.helper.WCallBack;
import com.mvp.ui.view.BaseTextWatcher;
import com.mvp.utils.DecimalUtil;
import com.mvp.utils.StringUtils;
import com.mvp.utils.ToastUtil;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.MemberBlanceRepository;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.credit.mvpview.WithdrawActivityView;
import com.wushi.lenovo.asia5b.app_di.credit.presenter.WithdrawActivityPresenter;
import com.wushi.lenovo.asia5b.app_model.credit.MemberBlanceModel;
import com.wushi.lenovo.asia5b.app_model.credit.WithdrawBankModel;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.trans.WithdrawDFragment;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;
import com.wushi.lenovo.asia5b.app_utils.eye.PopupListAdapter;
import com.wushi.lenovo.asia5b.app_utils.eye.PopupWindowHelper;
import com.wushi.lenovo.asia5b.app_utils.helper.CacheHelper;
import com.wushi.lenovo.asia5b.app_widget.ErrorTextView;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by zhangyuncai on 2019/1/16.
 * 提现
 */
public class WithdrawActivity extends BaseMvpActivity<WithdrawActivityView, WithdrawActivityPresenter> implements WithdrawActivityView {
    @BindView(R.id.et_withdraw_amount)
    EditText et_withdraw_amount;
    @BindView(R.id.tv_withdraw_amount_error)
    ErrorTextView tv_withdraw_amount_error;
    @BindView(R.id.tv_withdraw_spinner)
    TextView tv_withdraw_spinner;
    @BindView(R.id.tv_withdraw_spinner_error)
    ErrorTextView tv_withdraw_spinner_error;
    @BindView(R.id.et_withdraw_accontnumber)
    EditText et_withdraw_accontnumber;
    @BindView(R.id.tv_withdraw_accontnumber_error)
    ErrorTextView tv_withdraw_accontnumber_error;
    @BindView(R.id.et_withdraw_name)
    EditText et_withdraw_name;
    @BindView(R.id.tv_withdraw_name_error)
    ErrorTextView tv_withdraw_name_error;
    @BindView(R.id.et_withdraw_icnumber)
    EditText et_withdraw_icnumber;
    @BindView(R.id.tv_withdraw_icnumber_error)
    ErrorTextView tv_withdraw_icnumber_error;
    @BindView(R.id.bt_withdraw_proceed)
    Button bt_withdraw_proceed;
    @BindView(R.id.iv_withdraw_eye)
    ImageView iv_withdraw_eye;
    private PopupListAdapter<WithdrawBankModel> bankAdapter;
    private ListPopupWindow popupWindowBank;

    private String minText = "";//最低提现的文字提示
    private String maxText = "";//最低提现的文字提示
    private MemberBlanceModel memberBlanceModel;

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_withdraw;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        minText = String.format(getString(R.string.topup_notice_min), CacheHelper.loadCreditMinByLocal().getWithdraw_minimum_value());
        memberBlanceModel = MemberBlanceRepository.getMemberBalance();
        if (memberBlanceModel != null) {
            maxText = String.format(getString(R.string.topup_notice_max), memberBlanceModel.getBalance_value());
        }
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        et_withdraw_icnumber.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        bankAdapter = new PopupListAdapter<>(this, R.layout.item_popupitem_withdraw_adapter);
        popupWindowBank = PopupWindowHelper.getListPopupWindow(this, bankAdapter
                , tv_withdraw_spinner, ListPopupWindow.WRAP_CONTENT);
    }

    @Override
    protected void initData() {

    }

    private void submit() {
//        if (GlobalValue.isDebug) {
//            et_withdraw_amount.setText("101");
//            et_withdraw_accontnumber.setText("245555555556");
//            et_withdraw_name.setText("name");
//            et_withdraw_icnumber.setText("25567");
//        }
        boolean b = false;

        String amountText = et_withdraw_amount.getText().toString().trim();
        if (TextUtils.isEmpty(amountText)) {
            tv_withdraw_amount_error.setText(R.string.filed_is_empty);
            tv_withdraw_amount_error.setVisibility(View.VISIBLE);
            b = true;
        } else {
            float amount = StringUtils.parseFloat(amountText);
            String balanceValue="0";
            if(memberBlanceModel!=null) {
                balanceValue = memberBlanceModel.getBalance_value();
            }
            //如果提现后的余额
            String beforeBlance = DecimalUtil.subtract(balanceValue,amountText);
            float beforeBlanceF=StringUtils.parseFloat(beforeBlance);

            float withdraw_minimum_valueF = CacheHelper.loadCreditMinByLocal().getWithdraw_minimum_valueF();
            if (amount < withdraw_minimum_valueF) {
                tv_withdraw_amount_error.setVisibility(View.VISIBLE);
                tv_withdraw_amount_error.setText(minText);
                b = true;
            } else if (beforeBlanceF<0) {
                tv_withdraw_amount_error.setVisibility(View.VISIBLE);
                tv_withdraw_amount_error.setText(maxText);
                b = true;
            }
        }
        if (TextUtils.isEmpty(bankAdapter.getSelectItemText())) {
            b = true;
            tv_withdraw_spinner_error.setVisibility(View.VISIBLE);
        }

        String accountNumber = et_withdraw_accontnumber.getText().toString().trim();
        if (TextUtils.isEmpty(accountNumber)) {
            tv_withdraw_accontnumber_error.setVisibility(View.VISIBLE);
            b = true;
        }

        String name = et_withdraw_name.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            tv_withdraw_name_error.setVisibility(View.VISIBLE);
            b = true;
        }

        String icnumber = et_withdraw_icnumber.getText().toString().trim();
        if (TextUtils.isEmpty(icnumber)) {
            tv_withdraw_icnumber_error.setVisibility(View.VISIBLE);
            b = true;
        }

        MemberBlanceModel memberBlanceModel = MemberBlanceRepository.getMemberBalance();

        if (memberBlanceModel == null) {
            ToastUtil.showToast(getString(R.string.paymentfailed));
            b = true;
        }

        if (b) {
            return;
        }
        Map<String, Object> map = MapHelper.newHashMap();
        map.put("member_id", UserInfo.getMemberId());
        map.put("withdrawal_amount", amountText);
        map.put("holeded_bank", bankAdapter.getSelectItemText());
        map.put("bank_acc_no", accountNumber);
        map.put("account_holder_name", name);
        map.put("ic_number", icnumber);

        WithdrawDFragment withdrawDFragment = (WithdrawDFragment) WithdrawDFragment.instantiate(this, WithdrawDFragment.class.getName());
        withdrawDFragment.setData(map, memberBlanceModel, amountText);
        withdrawDFragment.show(getSupportFragmentManager(), getClass().getName());
        withdrawDFragment.setCallBack(new WCallBack<ResultModel>() {
            @Override
            public void callback(ResultModel resultModel) {
                if (resultModel.isSuccess()) {
                    withdrawDFragment.setOnDismissListener(dialog -> {
                        finish();
                    });
                }
            }
        });
    }

    @Override
    protected void initEvent() {
//        tv_withdraw_amount_error.setBindEditText(et_withdraw_amount);
        tv_withdraw_accontnumber_error.setBindEditText(et_withdraw_accontnumber);
        tv_withdraw_name_error.setBindEditText(et_withdraw_name);
        tv_withdraw_icnumber_error.setBindEditText(et_withdraw_icnumber);
        popupWindowBank.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popupWindowBank.dismiss();
                bankAdapter.setSelectPosition(position);
                tv_withdraw_spinner.setText(bankAdapter.getSelectItemText());
                tv_withdraw_spinner_error.setVisibility(View.GONE);
            }
        });
        EyeUtils.bindEye(iv_withdraw_eye, et_withdraw_icnumber);

        et_withdraw_amount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (TextUtils.isEmpty(et_withdraw_amount.getText().toString())) {
                        tv_withdraw_amount_error.setVisibility(View.VISIBLE);
                        tv_withdraw_amount_error.setText(minText);
                    }
                } else {
                    tv_withdraw_amount_error.setVisibility(View.GONE);
                }
            }
        });
        et_withdraw_amount.addTextChangedListener(new BaseTextWatcher() {
            @Override
            public void onTextChanged(CharSequence charSequence, int start, int count, int after) {
                super.onTextChanged(charSequence, start, count, after);
                if (TextUtils.isEmpty(charSequence)) {
                    tv_withdraw_amount_error.setVisibility(View.VISIBLE);
                    tv_withdraw_amount_error.setText(minText);
                } else {
                    tv_withdraw_amount_error.setVisibility(View.GONE);
                }
            }
        });
    }

    @OnClick({
            R.id.bt_withdraw_proceed,
            R.id.tv_withdraw_spinner/*,
            R.id.iv_withdraw_eye*/
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_withdraw_spinner:
                List<WithdrawBankModel> bankModels = bankAdapter.getmDatas();
                if (bankModels == null || bankModels.size() == 0) {
                    getPresenter().getBanks();
                }
                PopupWindowHelper.showPopupWindow(popupWindowBank);
                break;
            case R.id.bt_withdraw_proceed:
                submit();
                break;
            default:
                break;
        }

    }


    @Override
    public void getBanksResult(ResultModel<List<WithdrawBankModel>> listResultModel) {
        if (listResultModel.isSuccess()) {
            bankAdapter.setDatas(listResultModel.getData());
        }
    }

}
